<script setup>
import { ref, onMounted, nextTick, watch } from 'vue';
import { useRouter,useRoute } from 'vue-router';
import { CloseBold } from "@element-plus/icons-vue";
import AnnotationCard from "@/views/Reader/components/annotationCard.vue"; // 确保路径正确
import { getChapterContent } from '@/apis/getChapterContent';
const showAnnotation = ref(true);
const emit = defineEmits(['updateShowAnnotation','upodata']);
const radio1 = ref('1')
const renderAnnotation = (start, end) => {
  const range = document.createRange();
  const bodyTextElement = document.querySelector('.bodyText');
  const treeWalker = document.createTreeWalker(bodyTextElement, NodeFilter.SHOW_TEXT, null, false);
  let charCount = 0;
  let node;
  let startNode, startOffset, endNode, endOffset;

  while ((node = treeWalker.nextNode())) {
    const nodeLength = node.length;
    if (charCount + nodeLength >= start && !startNode) {
      startNode = node;
      startOffset = start - charCount;
    }
    if (charCount + nodeLength >= end && !endNode) {
      endNode = node;
      endOffset = end - charCount;
      break;
    }
    charCount += nodeLength;
  }

  if (startNode && endNode) {
    range.setStart(startNode, startOffset);
    range.setEnd(endNode, endOffset);
    const span = document.createElement('span');
    span.className = 'annotation';
    span.style.backgroundColor = 'rgba(255, 0, 0, 0.1)';
    span.style.borderBottom = '2px solid red';
    span.setAttribute('data-annotation-id', annotationId);
    annotationId++;

    range.surroundContents(span);

    highlightedText.value = bodyTextElement.innerHTML;
  }
};

const annotationArray = ref([
  {
    id: 1,
    name: 'yf',
    time: '2023-06-01 10:00',
    content: 'This is the first annotation.',
    imgUrl: 'https://softer-ware.oss-cn-beijing.aliyuncs.com/yf.jpg',
    type: 1
  },
  {
    id: 2,
    name: 'xxy',
    time: '2023-06-01 11:00',
    content: 'This is the second annotation.',
    imgUrl: 'https://softer-ware.oss-cn-beijing.aliyuncs.com/xxy.jpg',
    type: 1,
  },
  {
    id: 3,
    name: 'sxq',
    time: '2023-06-01 12:00',
    content: 'This is the third annotation.',
    imgUrl: 'https://softer-ware.oss-cn-beijing.aliyuncs.com/sxq.jpg'
  },
  {
    id: 4,
    name: 'wcb',
    time: '2023-06-01 13:00',
    content: 'This is the fourth annotation.',
    imgUrl: 'https://softer-ware.oss-cn-beijing.aliyuncs.com/wcb.jpg'
  },
  {
    id: 5,
    name: 'lfz',
    time: '2023-06-01 14:00',
    content: 'This is the fifth annotation.',
    imgUrl: 'https://softer-ware.oss-cn-beijing.aliyuncs.com/lfz.jpg'
  }
]);
const router = useRouter();
const route = useRoute();
const getChapterContentApi = async () => {
  const book_id = route.params.id;
  const chapterId = route.params.chapterId;
  const res = await getChapterContent(book_id,chapterId);
  console.log(res);
  annotationArray.value = res.data.annotation;
  console.log(annotationArray.value);
}

const highlightedAnnotation = ref(null);
const props = defineProps({
  annotationId: {
    type: Number
  },
  info:{
    
  }
});
watch(() => props.info, (newVal) => {
  if(newVal !== null){
    console.log(newVal);
    annotationArray.value.push(newVal);
  }
});
const closeAnnotation = () => {
  console.log('closeAnnotation is called');
  showAnnotation.value = false;
  emit('updateShowAnnotation', showAnnotation.value);
};

const removeAnnotation = (id) => {
  console.log('removeAnnotation is called');
  annotationArray.value = annotationArray.value.filter(annotation => annotation.id !== id);
};

const handleClick = (event, annotation) => {
  console.log('handleClick is called');
  getChapterContentApi()
  highlightedAnnotation.value = annotation;
  nextTick(() => {
    const element = document.getElementById(`annotation-${annotation.id}`);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  });
};

onMounted(() => {
  renderAnnotation(1, 10);
  console.log('onMounted is called asideAnnotation');
  document.addEventListener('click', (event) => {
    if (highlightedAnnotation.value && !event.target.closest('.annotationList')) {
      highlightedAnnotation.value = null;
    }
  });
});
</script>

<template>
  <div class="asideAnnotation" v-show="false">
    <div class="title">
      <p style="font-size: 20px; font-weight: bolder">批注</p>
      <el-radio-group v-model="radio1" class="ml-4">
        <el-radio value="1" size="large" @click="reserve(),emit('upodata',1)">私有</el-radio>
        <el-radio value="2" size="large" @click="reserve(),emit('upodata',2)">公开</el-radio>
      </el-radio-group>
      <el-icon @click="closeAnnotation">
        <CloseBold class="icon" />
      </el-icon>
    </div>
    <div class="annotationList">
      <div v-for="annotation in annotationArray" :key="annotation.id" @click.stop="handleClick($event, annotation)"
        :id="`annotation-${annotation.id}`"
        :class="{ highlighted: highlightedAnnotation && highlightedAnnotation.id === annotation.id }">
        <AnnotationCard :content="annotation" :annotationId="props.annotationId" @close="removeAnnotation" />
      </div>
      <div v-if="props.info !== null">
        <!-- <AnnotationCard :content="info.value" :annotationId=6 @close="removeAnnotation" /> -->
      </div>
    </div>
  </div>
</template>

<style scoped>
.asideAnnotation {
  display: flex;
  flex-direction: column;
  width: 300px;
  max-height: 100vh; /* 确保最大高度为视口高度 */
  overflow-y: auto;
  position: relative;
  background-color: white;
}

.title {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  position: sticky;
  top: 0;
  background-color: white;
  z-index: 1;
}

.icon {
  cursor: pointer;
}

.annotationList {
  overflow-y: auto;
  flex-grow: 1;
}

.highlighted {
  /* background-color: yellow; 设置高亮颜色 */
  transition: background-color 0.3s ease;
}
</style>